package com.yunfeisoft.business.service.impl;

import com.applet.base.BaseServiceImpl;
import com.applet.sql.separation.DataSourceChange;
import com.applet.utils.Page;
import com.yunfeisoft.business.dao.inter.*;
import com.yunfeisoft.business.model.*;
import com.yunfeisoft.business.service.inter.PurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * ClassName: PurchaseOrderServiceImpl
 * Description: 采购单信息service实现
 * Author: Jackie liu
 * Date: 2020-07-23
 */
@Service("purchaseOrderService")
public class PurchaseOrderServiceImpl extends BaseServiceImpl<PurchaseOrder, String, PurchaseOrderDao> implements PurchaseOrderService {

    @Autowired
    private PurchaseItemDao purchaseItemDao;
    @Autowired
    private PaymentRecordDao paymentRecordDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private WarehouseProductDao warehouseProductDao;

    @Override
    @DataSourceChange(slave = true)
    public Page<PurchaseOrder> queryPage(Map<String, Object> params) {
        return getDao().queryPage(params);
    }

    @Override
    public int modifyWithUnLock(String id, PurchaseOrder purchaseOrder) {
        //1 回退商品库存
        List<PurchaseItem> purchaseItemList = purchaseItemDao.queryByPurchaseOrderId(id);
        for (PurchaseItem item : purchaseItemList) {
            WarehouseProduct warehouseProduct = warehouseProductDao.loadSingle(item.getProductId(), item.getWarehouseId());

            WarehouseProduct product = new WarehouseProduct();
            product.setId(warehouseProduct.getId());
            product.setStock(warehouseProduct.getStock().subtract(item.getQuantity()));
            warehouseProductDao.update(product);
        }

        //2 减少供应商销售款
        purchaseOrder = purchaseOrder == null ? load(id) : purchaseOrder;
        Supplier supplier = supplierDao.load(purchaseOrder.getSupplierId());
        Supplier sup = new Supplier();
        sup.setId(supplier.getId());
        sup.setBalance(supplier.getBalance().subtract(purchaseOrder.getPayAmount()));
        supplierDao.update(sup);

        //3 删除付款记录
        paymentRecordDao.removeByPurchaseOrderId(id);

        PurchaseOrder order = new PurchaseOrder();
        order.setId(id);
        order.setStatus(PurchaseOrder.PurchaseOrderStatusEnum.TO_BE_CHANGED.getValue());
        order.setPayStatus(PurchaseOrder.PurchaseOrderPayStatusEnum.TO_BE_CLEARED.getValue());
        order.setPayAmount(BigDecimal.ZERO);
        return getDao().update(order);
    }

    @Override
    public int save(PurchaseOrder purchaseOrder) {
        //1 添加商品库存、添加商品记录
        Product pro = new Product();
        for (PurchaseItem item : purchaseOrder.getPurchaseItemList()) {
            WarehouseProduct warehouseProduct = warehouseProductDao.loadSingle(item.getProductId(), item.getWarehouseId());

            WarehouseProduct product = new WarehouseProduct();
            product.setId(warehouseProduct.getId());
            product.setStock(warehouseProduct.getStock().add(item.getQuantity()));
            warehouseProductDao.update(product);

            if (item.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal num = warehouseProduct.getStock().add(item.getQuantity());
                if (num.compareTo(BigDecimal.ZERO) <= 0) {
                    pro.setAvgPrice(item.getPrice());
                } else {
                    BigDecimal amount = warehouseProduct.getBuyPrice().multiply(warehouseProduct.getStock()).add(item.getAmount());
                    pro.setAvgPrice(amount.divide(num, 2, 4));
                }
            }

            //更新商品价格
            pro.setId(item.getProductId());
            pro.setBuyPrice(item.getPrice());
            productDao.update(pro);
        }
        purchaseItemDao.batchInsert(purchaseOrder.getPurchaseItemList());

        //2 增加供应商销售款
        Supplier supplier = supplierDao.load(purchaseOrder.getSupplierId());
        Supplier sup = new Supplier();
        sup.setId(supplier.getId());
        sup.setBalance(purchaseOrder.getPayAmount().add(supplier.getBalance()));
        supplierDao.update(sup);

        //3 添加付款记录
        if (purchaseOrder.getPaymentRecord() != null) {
            paymentRecordDao.insert(purchaseOrder.getPaymentRecord());
        }

        return super.save(purchaseOrder);
    }

    @Override
    public int modify(PurchaseOrder purchaseOrder) {
        PurchaseOrder order = getDao().load(purchaseOrder.getId());
        if (order.getStatus() == PurchaseOrder.PurchaseOrderStatusEnum.STORAGED.getValue()) {
            modifyWithUnLock(order.getId(), order);
        }

        //1 扣减商品库存、删除老商品、添加新商品
        purchaseItemDao.removeByPurchaseOrderId(purchaseOrder.getId());

        Product pro = new Product();
        for (PurchaseItem item : purchaseOrder.getPurchaseItemList()) {
            WarehouseProduct warehouseProduct = warehouseProductDao.loadSingle(item.getProductId(), item.getWarehouseId());

            WarehouseProduct product = new WarehouseProduct();
            product.setId(warehouseProduct.getId());
            product.setStock(warehouseProduct.getStock().add(item.getQuantity()));
            warehouseProductDao.update(product);

            if (item.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal num = warehouseProduct.getStock().add(item.getQuantity());
                if (num.compareTo(BigDecimal.ZERO) <= 0) {
                    pro.setAvgPrice(item.getPrice());
                } else {
                    BigDecimal amount = warehouseProduct.getBuyPrice().multiply(warehouseProduct.getStock()).add(item.getAmount());
                    pro.setAvgPrice(amount.divide(num, 2, 4));
                }
            }

            //更新商品价格
            pro.setId(item.getProductId());
            pro.setBuyPrice(item.getPrice());
            productDao.update(pro);
        }
        purchaseItemDao.batchInsert(purchaseOrder.getPurchaseItemList());

        //2 增加客户销售款
        Supplier supplier = supplierDao.load(purchaseOrder.getSupplierId());
        Supplier sup = new Supplier();
        sup.setId(supplier.getId());
        sup.setBalance(purchaseOrder.getPayAmount().add(supplier.getBalance()));
        supplierDao.update(sup);

        //3 添加付款记录
        if (purchaseOrder.getPaymentRecord() != null) {
            paymentRecordDao.insert(purchaseOrder.getPaymentRecord());
        }
        return super.modify(purchaseOrder);
    }

    @Override
    public int remove(String id) {
        PurchaseOrder purchaseOrder = load(id);
        if (purchaseOrder.getStatus() == PurchaseOrder.PurchaseOrderStatusEnum.STORAGED.getValue()) {
            //1 回退商品库存
            List<PurchaseItem> purchaseItemList = purchaseItemDao.queryByPurchaseOrderId(id);
            for (PurchaseItem item : purchaseItemList) {
                WarehouseProduct warehouseProduct = warehouseProductDao.loadSingle(item.getProductId(), item.getWarehouseId());

                WarehouseProduct product = new WarehouseProduct();
                product.setId(warehouseProduct.getId());
                product.setStock(warehouseProduct.getStock().subtract(item.getQuantity()));
                warehouseProductDao.update(product);
            }

            //2 减少供应商销售款
            Supplier supplier = supplierDao.load(purchaseOrder.getSupplierId());
            Supplier sup = new Supplier();
            sup.setId(supplier.getId());
            sup.setBalance(supplier.getBalance().subtract(purchaseOrder.getPayAmount()));
            supplierDao.update(sup);
        }

        //1 删除商品
        purchaseItemDao.removeByPurchaseOrderId(id);
        //2 删除付款记录
        paymentRecordDao.removeByPurchaseOrderId(id);

        return super.remove(id);
    }

    @Override
    public int remove(String[] ids) {
        for (String id : ids) {
            remove(id);
        }
        return super.remove(ids);
    }

    @Override
    public PurchaseOrder queryTotalAmount(String orgId, int status, int payStatus) {
        return getDao().queryTotalAmount(orgId, status, payStatus);
    }

}